package com.hospital.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hospital.configure.Result;
import com.hospital.entity.*;
import com.hospital.mapper.*;
import com.hospital.service.CaseInfoService;
import com.hospital.utils.IDGenerator;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author WuLiting
 * @since 2021-03-24
 */
@Service
public class CaseInfoServiceImpl extends ServiceImpl<CaseInfoMapper, CaseInfo> implements CaseInfoService {

    @Resource
    CaseInfoMapper caseInfoMapper;

    @Resource
    CaseMedicineMapper caseMedicineMapper;

    @Resource
    FeeRecordMapper feeRecordMapper;

    @Resource
    UserMapper userMapper;

    @Resource
    MedicineMapper medicineMapper;

    @Override
    public Result<CaseInfo> updateCaseInfo(CaseInfo caseInfo) {
        Result<CaseInfo> result = new Result<>();
        try {
            if (StringUtils.isEmpty(caseInfo.getCaseInfoId())) {
                //如果ID为空，代表添加
                caseInfo.setCaseInfoId(IDGenerator.getUUID("CASE"));
                caseInfo.setCreateTime(new Date());
                caseInfoMapper.insert(caseInfo);

                if (caseInfo.getMedicineList() != null && caseInfo.getMedicineList().size() != 0) {
                    for (CaseMedicine caseMedicine : caseInfo.getMedicineList()) {
                        caseMedicine.setCaseMedicineId(IDGenerator.getUUID("CAME"));
                        caseMedicine.setCaseId(caseInfo.getCaseInfoId());
                        caseMedicineMapper.insert(caseMedicine);
                    }
                }
            } else {
                //如果ID不为空，代表修改
                caseInfoMapper.updateById(caseInfo);
                QueryWrapper<CaseMedicine> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda().eq(CaseMedicine::getCaseId, caseInfo.getCaseInfoId());
                caseMedicineMapper.delete(queryWrapper);

                if (caseInfo.getMedicineList() != null && caseInfo.getMedicineList().size() != 0) {
                    for (CaseMedicine caseMedicine : caseInfo.getMedicineList()) {
                        caseMedicine.setCaseMedicineId(IDGenerator.getUUID("CAME"));
                        caseMedicine.setCaseId(caseInfo.getCaseInfoId());
                        caseMedicineMapper.insert(caseMedicine);
                    }
                }
            }
            result.setMessage("success");
        } catch (Exception e) {
            result.setMessage(e.getMessage());
        }
        return result;
    }

    @Override
    public Result<CaseInfo> delCaseInfo(CaseInfo caseInfo) {
        Result<CaseInfo> result = new Result<>();
        try {
            if (StringUtils.isEmpty(caseInfo.getCaseInfoId())) {
                result.setMessage("caseInfoId can't be empty");
                return result;
            }
            caseInfoMapper.deleteById(caseInfo.getCaseInfoId());
            result.setMessage("success");
        } catch (Exception e) {
            result.setMessage(e.getMessage());
        }
        return result;
    }

    @Override
    public Result<CaseInfo> batchDelCaseInfo(CaseInfo caseInfo) {
        Result<CaseInfo> result = new Result<>();
        try {
            if (!StringUtils.isEmpty(caseInfo.getIds())) {
                String[] ids = caseInfo.getIds().split(",");
                for (String id : ids) {
                    caseInfoMapper.deleteById(id);
                }
            }
        } catch (Exception e) {
            result.setMessage(e.getMessage());
        }
        return result;
    }

    @Override
    public Result<CaseInfo> queryCaseInfo(CaseInfo caseInfo) {
        Result<CaseInfo> result = new Result<>();
        try {
            QueryWrapper<CaseInfo> wrapper = new QueryWrapper<>();
            //查询条件拼接，仅限单表查询可用


            List<CaseInfo> caseInfos = caseInfoMapper.selectList(wrapper);
            result.setReturnList(caseInfos);
            result.setMessage("success");
        } catch (Exception e) {
            result.setMessage(e.getMessage());
        }
        return result;
    }

    @Override
    public Result queryCaseInfoByPage(CaseInfo caseInfo) {
        Result<CaseInfo> result = new Result<>();

        try {
            if (caseInfo.getCurrent() == null || caseInfo.getSize() == null) {
                result.setMessage("current or size can't be null");
                return result;
            }

            Page<CaseInfo> caseInfos = caseInfoMapper.queryCaseInfoByPage(new Page<>(caseInfo.getCurrent(), caseInfo.getSize()), caseInfo);
//            caseInfos.setRecords(null);
            result.setReturnPage(caseInfos);
            result.setMessage("success");
        } catch (Exception e) {
            result.setMessage(e.getMessage());
        }
        return result;
    }

    @Override
    public Result<CaseInfo> queryCaseInfoById(CaseInfo caseInfo) {
        Result<CaseInfo> result = new Result<>();
        try {
            CaseInfo returnCaseInfo = caseInfoMapper.selectById(caseInfo.getCaseInfoId());
            result.setReturnObj(returnCaseInfo);
            result.setMessage("success");
        } catch (Exception e) {
            result.setMessage(e.getMessage());
        }
        return result;
    }

    @Override
    public Result<Registered> queryRegisteredUserByDoctorId(Registered registered) {
        Result<Registered> result = new Result<>();
        try {
            List<Registered> registereds = caseInfoMapper.queryRegisteredUserByDoctorId(registered.getDoctorId());
            result.setReturnList(registereds);
            result.setMessage("success");
        } catch (Exception e) {
            result.setMessage(e.getMessage());
        }
        return result;
    }

    @Override
    public Result<CaseInfo> caseInfoPay(CaseInfo caseInfo) {
        Result<CaseInfo> result = new Result<>();
        try {
            caseInfo.setCaseStatus("1");//诊断状态那里，已结束还是诊断中耶
            caseInfoMapper.updateById(caseInfo);

            //添加药品费用记录:姓名，付款类别，付款数，收款人，收款时间，支付宝账单，备注
            FeeRecord feeRecord = new FeeRecord();
            feeRecord.setUserId(caseInfo.getUserId());
            feeRecord.setUserName(userMapper.selectById(caseInfo.getUserId()).getUserName());
            feeRecord.setFeeType("药品费用");
            feeRecord.setCreateUser(caseInfo.getDoctorId());
            feeRecord.setCreateUserName(userMapper.selectById(caseInfo.getDoctorId()).getUserName());

            QueryWrapper<CaseMedicine> wrapper = new QueryWrapper<>();
            wrapper.lambda().eq(CaseMedicine::getCaseId, caseInfo.getCaseInfoId());

            List<CaseMedicine> caseMedicines = caseMedicineMapper.selectList(wrapper);

            Double totalAmount = 0d;
            //到药品啦药品数量的变动啦啦
            for (CaseMedicine caseMedicine : caseMedicines) {
                Medicine medicine = medicineMapper.selectById(caseMedicine.getMedicineId());
                medicine.setAmount(medicine.getAmount() - caseMedicine.getAmount());
                totalAmount += medicine.getAmount() * medicine.getPrice();
                medicineMapper.updateById(medicine);
            }
            feeRecord.setRecordId(IDGenerator.getUUID("FEERECORD"));
            feeRecord.setFeeAmount(totalAmount);
            feeRecord.setCreateTime(new Date());
            feeRecord.setTradeNo("线下支付");
            feeRecord.setOrderId(caseInfo.getCaseInfoId());
            feeRecord.setRemark("线下支付");
            feeRecordMapper.insert(feeRecord);
            result.setMessage("success");
        } catch (Exception e) {
            result.setMessage(e.getMessage());
        }
        return result;
    }

}
